package org.batatasframework.web.element;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.batatasframework.web.HtmlRenderHelper;


public class AbstractElement {
	
	protected final String name;
	protected HtmlAttribute attribute;
	/** 有可能是href或src等属性的值 */
	private String url;
	
	private Map<String, Object> clientAttributes;

	public AbstractElement(String name){
		this.name = name;
	}
	
	/** 添加在节点上的属性值 */
	public void addAttribute(String name, Object value){
		if(null == clientAttributes) clientAttributes = new HashMap<>();
		
		clientAttributes.put(name, value);
	}
	
	public void setAttribute(HtmlAttribute attribute) {
		this.attribute = attribute;
	}
	
	/** {@link HtmlAttribute}对象可能为空 */
	public HtmlAttribute getAttribute() {
		return attribute;
	}

	/** {@link HtmlAttribute}对象不为空，会自动创建新对象 */
	public HtmlAttribute attribute() {
		if(null == attribute) attribute = new HtmlAttribute();
		return attribute;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}
	
	protected String getUrlAttributeName(){
		return "href";
	}

	@Override
	public String toString(){
		StringBuilder html = new StringBuilder();
		html.append('<').append(name);
		readAttribute(html);
		elementClosed(html);
		return html.toString();
	}
	
	protected void readAttribute(StringBuilder html){
		if(null != attribute){
			attribute.parseAttribute(html);
		}
		if(null != clientAttributes){
			for(Entry<String, Object> entry : clientAttributes.entrySet()){
				HtmlRenderHelper.attribute(html, entry.getKey(), entry.getValue(), false);
			}
		}
		if(null != url){
			HtmlRenderHelper.attribute(html, getUrlAttributeName(), url, false);
		}
	}
	
	/** 一个元素的结束部分 */
	protected void elementClosed(StringBuilder html){
		html.append("/>");
	}
}
